<template>
  <MdEditor
    v-model="text"
    ref="editorRef"
    @onSave="onSave"
    @onUploadImg="onUploadImg"
  />
</template>

<script setup>
import request from '@/utils/request'
import { ref, watch, onMounted } from 'vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import usemdDataStore from '@/store/mdData'
const text = ref('OI')
watch(text, (newa, old) => {
  console.log(newa)
  usemdDataStore.mdData = text.value
})
const onSave = (v, h) => {
  console.log(v)
  h.then((html) => {
    let testV = { test: v, hvalue: html }
    const result = request
      .post('http://127.0.0.1:8888/api/addArticle', testV, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      .then((result) => {
        console.log(result)
      })
      .catch((err) => {
        console.log('------------------------')
      })
  })
}
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      console.log(file)
      return new Promise((rev, rej) => {
        const form = new FormData()
        form.append('file', file)
        console.log('上传启动！')
        request
          .post('http://127.0.0.1:8888/api/upload', form, {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          })
          .then((res) => rev(res))
          .catch((error) => rej(error))
      })
    }),
  )

  callback(res.map((item) => item.url))
}
onMounted(() => {
  let result = request
    .post('http://127.0.0.1:8888/api/getArticles')
    .then((result) => {
      console.log(typeof result.data)
      console.log(result)
      let da = JSON.stringify(result.data.article_content)
      da = da.slice(1, -1)
      da = da.replace(/\\n/g, '\n')
      console.log(da)
      text.value = da
    })
    .catch((err) => {
      console.log(err)
    })
})
</script>
